<template>
  <section class="wrap">
    <el-form ref="ruleForm" :model="ruleForm" label-width="120px" class="demo-ruleForm">
      <el-form-item v-for="item in config" :key="item.id" :label="getLabel(item.name)" :prop="item.name">
        <el-input v-model.number="ruleForm[item.name]" type="number" :placeholder="`请输入${getLabel(item.name)}`">
          <template v-if="item.name === 'yajin'" #append>元</template>
          <template v-if="item.name === 'fadan' || 'gongsi'" #append>%</template>
        </el-input>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" :loading="submitting" @click="submitForm">
          立即更新
        </el-button>
      </el-form-item>
    </el-form>
  </section>
</template>

<script>
import configApi from '@/plugins/api/config'

export default {
  data() {
    return {
      config: [],
      ruleForm: {
        yajin: 0,
        fadan: 0
      },
      submitting: false
    }
  },
  created() {
    this.getConfig()
  },
  methods: {
    // 获取参数名称对应的中文标签
    getLabel(name) {
      const labelMap = {
        yajin: '押金设置',
        fadan: '发单比例设置',
        gongsi: '公司比例设置'
      }
      return labelMap[name] || name
    },

    // 获取配置数据
    async getConfig() {
      try {
        const res = await configApi.list()
        if (res.code === 200) {
          this.config = res.data
          // 初始化表单数据
          this.config.forEach(item => {
            this.$set(this.ruleForm, item.name, Number(item.value) || 0)
          })
        }
      } catch (error) {
        console.error('获取配置失败:', error)
        this.$message.error('获取配置失败')
      }
    },

    // 提交表单
    async submitForm() {
      this.submitting = true
      try {
        // 构建提交数据
        const submitData = this.config.map(item => ({
          id: item.id,
          name: item.name,
          value: this.ruleForm[item.name]
        }))

        console.log('提交数据:', submitData)

        // 实际API调用
        for (let index = 0; index < submitData.length; index++) {
          
          const res = await configApi.modify(submitData[index])
          if (res.code === 200 && index === submitData.length -1) {
            this.$message.success('更新成功')
            this.getConfig() // 刷新数据
          } 
          if (res.code !== 200) {
            this.$message.error(res.msg || '更新失败')
          }

        }
      } catch (error) {
        console.error('更新失败:', error)
        this.$message.error('更新失败')
      } finally {
        this.submitting = false
      }
    }
  }
}
</script>
  
<style scoped lang="scss">
.wrap {
  box-sizing: border-box;
  margin: 24px;
}
</style>
  
  